import { computed, type Ref } from 'vue'
import { useTreeStore, type ProjectTreeNode } from '@/store/modules/tree'

export interface SimpleNodeOption { key: string; name: string }

/**
 * 简化节点收集：遍历整棵树，返回指定类型的所有节点 key/name 列表。
 */
export function useAvailableSets(projectIdRef: Ref<string | number | null | undefined>, type: string) {
  const treeStore = useTreeStore()
  const availableSets = computed<SimpleNodeOption[]>(() => {
    const pid = projectIdRef.value
    if (pid == null) return []
    const tree = treeStore.getTree(pid)
    if (!Array.isArray(tree) || !tree.length) return []
    const result: SimpleNodeOption[] = []
    const stack: ProjectTreeNode[] = [...tree]
    while (stack.length) {
      const node = stack.pop()!
      if (node.type === type && node.name) {
        result.push({ key: node.key, name: node.name })
      }
      if (node.children && node.children.length) stack.push(...node.children)
    }
    return result
  })
  return { availableSets }
}
